package com.yj.inventory.service;

import com.yj.common.enums.OAUserRoleLevel;
import com.yj.common.mapper.PaginationMapper;
import com.yj.config.mybatis.pagination.Page;
import com.yj.inventory.dto.InventoryListDto;
import com.yj.inventory.dto.InventoryUpdateDto;
import com.yj.inventory.entity.Inventory;
import com.yj.inventory.entity.InventoryHistory;
import com.yj.inventory.mapper.InventoryHistoryMapper;
import com.yj.inventory.mapper.InventoryMapper;
import com.yj.oa.entity.system.OAUserInfo;
import com.yj.oa.service.OAInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Copyright 2017 (C) Yunjian-VC
 * Created on : 2017/12/12
 * Author     : Unbelievable9
 **/
@Service
public class InventoryService {

    @Autowired
    InventoryMapper inventoryMapper;

    @Autowired
    InventoryHistoryMapper inventoryHistoryMapper;

    @Autowired
    PaginationMapper paginationMapper;

    @Autowired
    OAInfoService oaInfoService;

    public Boolean userValidation(String token) {
        OAUserInfo oaUserInfo = oaInfoService.getOAUserByToken(token);

        return oaUserInfo != null && oaUserInfo.getRole_level().equals(OAUserRoleLevel.OPERATOR);
    }

    @Transactional
    public void createInventory(Inventory inventory, String token) {
        OAUserInfo oaUserInfo = oaInfoService.getOAUserByToken(token);
        inventory.setUser_id(oaUserInfo.getUser_id());

        inventoryMapper.insert(inventory);

        InventoryHistory inventoryHistory = new InventoryHistory();
        inventoryHistory.setInventory_id(inventory.getId());
        inventoryHistory.setAmount(inventory.getAmount());
        inventoryHistory.setUpdate_time(inventory.getRecord_time());

        inventoryHistoryMapper.insert(inventoryHistory);
    }

    @Transactional
    public void updateInventory(InventoryUpdateDto inventoryUpdateDto, String token) {
        inventoryMapper.update(inventoryUpdateDto);

        InventoryHistory inventoryHistory = new InventoryHistory();
        inventoryHistory.setInventory_id(inventoryUpdateDto.getId());
        inventoryHistory.setAmount(inventoryUpdateDto.getAmount());
        inventoryHistory.setUpdate_time(inventoryUpdateDto.getRecord_time());

        inventoryHistoryMapper.insert(inventoryHistory);
    }

    public List<InventoryHistory> getInventoryHistoryByID(Integer id) {
        return inventoryHistoryMapper.getByInventoryID(id);
    }

    public Page<Inventory> getInventoryList(InventoryListDto inventoryListDto, String token) {
        OAUserInfo oaUserInfo = oaInfoService.getOAUserByToken(token);
        inventoryListDto.setUser_id(oaUserInfo.getUser_id());

        return paginationMapper.getInventoryList(inventoryListDto);
    }
}
